package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"video/models"
)

type VideoController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *VideoController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Add() {
	title := c.GetString("title")
	name := c.GetString("name")
	address := c.GetString("address")
	times := time.Now()
	video := models.Video{
		Title:   title,
		Name:    name,
		Address: address,
		Times:   times,
	}
	err := models.DB.Create(&video).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	title := c.GetString("title")
	videos, total, err := models.ListVideo(page, pageSize, title)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "分页查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		JosnSrc := make(map[string]interface{})
		JosnSrc["videos"] = videos
		JosnSrc["total"] = total
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "分页查询成功",
			Data: JosnSrc,
		}
		c.ServeJSON()
	}

}
